package com.d.common.utils;

import com.dtflys.forest.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {
    public static String nick_error_message = "昵称只允许输入2-20位字符，支持中英文、数字及 -	_ @ 组合";
    public static String nick_error_words = "您输入的昵称含有非法字符";

    /**
     * 获取MD5
     * <功能详细描述>
     *
     * @param sourceStr
     * @return
     * @author
     * @date
     * @see [类、类#方法、类#成员]
     */
    public static String getMD5(String sourceStr) {
        String resultStr = "";
        try {
            byte[] temp = sourceStr.getBytes();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(temp);
            // resultStr = new String(md5.digest());
            byte[] b = md5.digest();
            for (int i = 0; i < b.length; i++) {
                char[] digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
                        '9', 'A', 'B', 'C', 'D', 'E', 'F'};
                char[] ob = new char[2];
                ob[0] = digit[(b[i] >>> 4) & 0X0F];
                ob[1] = digit[b[i] & 0X0F];
                resultStr += new String(ob);
            }
            return resultStr;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static String getPassword6() {
        Random random = new Random();
        Integer num = random.nextInt(990000 - 110000) + 110000;
        return num.toString();
    }

    /**
     * 获取UUID
     *
     * @return
     * @author
     * @date 2015年7月3日 上午10:07:41
     * @see [类、类#方法、类#成员]
     */
    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replace("-", "");
    }


    /**
     * 刷新redis登录时间为7天
     *
     * @param token
     * @return
     * @author
     * @date
     * @see [类、类#方法、类#成员]
     */
    public static boolean refreshLogin(String token) {
        try {
            String custId = RedisUtil.getJedisVal(token);
            if (StringUtils.isBlank(custId)) {
                return false;
            }
            RedisUtil.setJedisVal(token, custId, 604800);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 判断手机号是否正确
     *
     * @param mobiles
     * @return
     * @author
     * @date
     * @see [类、类#方法、类#成员]
     */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(14[5,7])|(15[^4,\\D])|(17[0,6-9])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 验证密码
     *
     * @param password
     * @return
     * @author
     * @date
     * @see [类、类#方法、类#成员]
     */
    public static boolean checkPassword(String password) {
        Pattern p = Pattern.compile("^[a-zA-Z0-9\\d~!@#$%^&*()_+-={}\\[\\]\\?/,.]{6,20}$");
        Matcher m = p.matcher(password);
        return m.matches();
    }


    /**
     * 转Unicode编码
     *
     * @param str
     * @return
     * @author
     * @date
     * @date 2015年9月5日 下午3:06:51
     * @see [类、类#方法、类#成员]
     */
    public static String string2Unicode(String str) {
        str = (str == null ? "" : str);
        String tmp;
        StringBuffer sb = new StringBuffer();
        char c;
        int i, j;
        sb.setLength(0);
        for (i = 0; i < str.length(); i++) {
            c = str.charAt(i);
            sb.append("\\u");
            j = (c >>> 8); // 取出高8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);
            j = (c & 0xFF); // 取出低8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);

        }
        return (new String(sb));
    }

    /**
     * 收货人名称必须为中文
     *
     * @param a
     * @return
     * @author
     * @date
     * @see [类、类#方法、类#成员]
     */
    public static boolean checkReceiverName(String a) {
        Pattern p = Pattern.compile("^[\u4e00-\u9fa5]{2,10}$");
        Matcher m = p.matcher(a);
        return m.matches();
    }

    /**
     * 收货人名称必须为中文
     *
     * @param a
     * @return
     * @author
     * @date 2015年12月9日 上午11:44:22
     * @see [类、类#方法、类#成员]
     */
    public static boolean checkReceiverAddress(String a) {
        Pattern p1 = Pattern.compile("^.*[\u4e00-\u9fa5].*$");  //先验证是否至少有一个中文
        Matcher m1 = p1.matcher(a);
        if (m1.matches()) {
            Pattern p = Pattern.compile("^[a-zA-Z0-9 \u4e00-\u9fa5\\d#()（）-]+$");
            Matcher m = p.matcher(a);
            return m.matches();
        } else {
            return false;
        }

    }
    /**
     * 根据token获取用户信息
     * @author
     * @date
     * @param token
     * @return
     * @see [类、类#方法、类#成员]
     */
//	public static CustomerDO getCustomerForRedis(String token){
//		try {
//			if(StringUtils.isBlank(token)){
//				return null;
//			}
//			String custId= RedisUtil.getJedisVal(token);
//			if(StringUtils.isBlank(custId)){
//				return null;
//			}
//			String custJson= RedisUtil.getJedisVal(custId);
//			if(StringUtils.isBlank(custJson)){
//				return null;
//			}
//			RedisUtil.setJedisVal(token, custId);
//			return GsonUtil.fromJson(custJson, CustomerDO.class);
//		} catch (Exception e) {
//			return null;
//		}
//	}

//	public static CustomerDO getCustomerForId(String custId){
//		try {
//			String custJson= RedisUtil.getJedisVal(custId);
//			if(StringUtils.isBlank(custJson)){
//                return null;
//            }
//			return GsonUtil.fromJson(custJson, CustomerDO.class);
//		} catch (Exception e) {
//			return null;
//		}
//	}

    /**
     * 随机指定范围内N个不重复的数
     * 最简单最基本的方法
     *
     * @param min 指定范围最小值
     * @param max 指定范围最大值
     */
    public static int random(int min, int max) {
        return (int) (min + Math.random() * (max - min + 1));
    }

    /**
     * 密码盐值加密
     *
     * @param password
     * @param salt
     * @return
     */
    public static String encryptPassword(String password, String salt) {
        return getMD5(password + salt);
    }

    /**
     * 重庆时时彩,期次推算
     *
     * @param date
     * @return
     */
    public static String getCqssNo(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        if (cal.get(Calendar.SECOND) != 0) {
            cal.add(Calendar.MINUTE, 6);
        } else {
            cal.add(Calendar.MINUTE, 5);
        }

        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);

        Integer caileleNo = 0;

        if (hour == 23 || hour == 0 || hour == 1) {
            int x = 0;
            if (minute % 5 != 0) {
                x = 1;
            }
            if (hour != 1 || minute <= 55) {
                if (hour == 0 && minute == 0) {
                    caileleNo = 120;
                } else {
                    if (hour == 23) {
                        caileleNo = 108 + (minute / 5) + x;
                    } else {
                        caileleNo = hour * 12 + (minute / 5) + x;
                    }

                }
            }
        } else if (hour >= 10 && hour <= 22) {
            int x = 0;
            if (minute % 10 != 0) {
                x = 1;
            }
            caileleNo = 24 + (hour - 10) * 6;
            if (hour == 22) {
                caileleNo = caileleNo + (minute / 5 + x);
            } else {
                caileleNo = caileleNo + (minute / 10 + x);
            }
        }

        String getCqssNo = "";
        if (caileleNo < 10 && caileleNo != 0) {
            getCqssNo = UtilDate.DateToString(cal.getTime(), "yyyyMMdd") + "00" + caileleNo;
        } else if (caileleNo >= 10 && caileleNo < 100) {
            getCqssNo = UtilDate.DateToString(cal.getTime(), "yyyyMMdd") + "0" + caileleNo;
        } else if (caileleNo >= 100 && caileleNo <= 120) {
            getCqssNo = UtilDate.DateToString(cal.getTime(), "yyyyMMdd") + caileleNo;
        } else if (caileleNo == 0) {
            getCqssNo = UtilDate.DateToString(date, "yyyyMMdd") + "024";
        }
        return getCqssNo;
    }

    /**
     * 获取分享号
     *
     * @param custid
     * @return
     */
    public static String getShareNo(Integer custid) {
        String input = String.format("%010d", custid);
        String rc = HloveyRC4(input, Utils.getUUID());
        //转换为16位
        String returnStr = "";
        for (int x = 0; x < rc.length(); x++) {
            int ch = (int) rc.charAt(x);
            String s = Integer.toHexString(ch);
            returnStr = returnStr + s;
        }

        return returnStr.toUpperCase();
    }

    /**
     * RC4加密
     *
     * @param aInput
     * @param aKey
     * @return
     */
    public static String HloveyRC4(String aInput, String aKey) {
        int[] iS = new int[256];
        byte[] iK = new byte[256];

        for (int i = 0; i < 256; i++)
            iS[i] = i;

        int j = 1;

        for (short i = 0; i < 256; i++) {
            iK[i] = (byte) aKey.charAt((i % aKey.length()));
        }

        j = 0;

        for (int i = 0; i < 255; i++) {
            j = (j + iS[i] + iK[i]) % 256;
            int temp = iS[i];
            iS[i] = iS[j];
            iS[j] = temp;
        }


        int i = 0;
        j = 0;
        char[] iInputChar = aInput.toCharArray();
        char[] iOutputChar = new char[iInputChar.length];
        for (short x = 0; x < iInputChar.length; x++) {
            i = (i + 1) % 256;
            j = (j + iS[i]) % 256;
            int temp = iS[i];
            iS[i] = iS[j];
            iS[j] = temp;
            int t = (iS[i] + (iS[j] % 256)) % 256;
            int iY = iS[t];
            char iCY = (char) iY;
            iOutputChar[x] = (char) (iInputChar[x] ^ iCY);
        }

        return new String(iOutputChar);

    }

    /**
     * 获取用户真是访问IP
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("PRoxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (StringUtils.isNotBlank(ip)) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    /**
     * 获取重庆时时彩对应的开奖时间
     *
     * @param period
     * @return
     */
    public static Date getCqssDate(String period) {
        String no = period.substring(8);
        int hour = 0;
        int minute = 0;
        int i = Integer.parseInt(no);
        if (i <= 23) {
            hour = i * 5 / 60;
            minute = i * 5 % 60;
        } else if (i <= 96) {
            i = i - 24;
            hour = 10 + (i * 10 / 60);
            minute = i * 10 % 60;
        } else if (i < 120) {
            i = i - 96;
            hour = 22 + (i * 5 / 60);
            minute = i * 5 % 60;
        } else if (i == 120) {
            hour = 0;
            minute = 0;
        }
        Date date = UtilDate.stringToDate(period.substring(0, 8) + String.format("%02d", hour) + String.format("%02d", minute) + "00", "yyyyMMddHHmmss");
        if (i == 120) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.DAY_OF_YEAR, 1);
            date = cal.getTime();
        }
        return date;
    }

    public static void main(String[] args) {
//		String url="http://data.shishicai.cn/cqssc/haoma";
//		//解析html
//		try {
//			Connection.Response res= Jsoup.connect(url).timeout(10000).execute();
//			Map<String,String> cookies=res.cookies();
////			for (Map.Entry entry:cookies.entrySet()) {
////				String key = entry.getKey().toString();
////				String value = entry.getValue().toString();
////				System.out.println("key=" + key + " value=" + value);
////			}
//			String doc=Jsoup.connect("http://data.shishicai.cn/handler/kuaikai/data.ashx")
//					.header("Accept","*/*")
//					.header("Accept-Encoding","gzip, deflate")
//					.header("Accept-Language","zh-CN,zh;q=0.8,en;q=0.6")
//					.header("Cache-Control","max-age=0")
//					.header("Connection","keep-alive")
//					.header("Content-Length","25")
//					.header("Content-Type","application/x-www-form-urlencoded")
//					.header("Host","data.shishicai.cn")
//					.header("Origin","http://data.shishicai.cn")
//					.header("Referer","http://data.shishicai.cn/cqssc/haoma/")
//					.header("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36")
//					.header("X-Requested-With","XMLHttpRequest")
//					.data("lottery","4")
//					.data("date","00001-01-01")
//					.cookies(cookies).post().text();
//			List<String> list=GsonUtil.fromJson(doc,new TypeToken<List<String>>(){}.getType());
//			for(int i=0;i<list.size()-1;i++){
//				String[] strs=list.get(i).split(";");
//				System.out.println("期次:"+strs[0]+" 中奖号:"+strs[1]+" 开奖时间:"+strs[2]);
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		TaobaoIp taobaoIp=Utils.getIpInfo("221.208.244.214");
//		System.out.println(taobaoIp.getData().getCity());
    }

    public static <T> List<List<T>> split(List<T> resList, int count) {
        if ((resList == null) || (count < 1)) {
            return null;
        }
        List<List<T>> ret = new ArrayList();
        int size = resList.size();
        if (size <= count) {
            ret.add(resList);
        } else {
            int pre = size / count;
            int last = size % count;
            for (int i = 0; i < pre; i++) {
                List<T> itemList = new ArrayList();
                for (int j = 0; j < count; j++) {
                    itemList.add(resList.get(i * count + j));
                }
                ret.add(itemList);
            }
            if (last > 0) {
                List<T> itemList = new ArrayList();
                for (int i = 0; i < last; i++) {
                    itemList.add(resList.get(pre * count + i));
                }
                ret.add(itemList);
            }
        }
        return ret;
    }

    /**
     * 将用户信息加入缓存 返回key
     * @author
     * @date
     * @param jedisval
     * @return
     * @see [类、类#方法、类#成员]
     */
//	public static String custSetRedis(String jedisval){
//		CustomerDO customer= GsonUtil.fromJson(jedisval, CustomerDO.class);
//		String key= Utils.getUUID();
//		while (RedisUtil.getJedisVal(key)!=null) {
//			key= Utils.getUUID();
//		}
//		RedisUtil.setJedisVal(key, customer.getCustId().toString());
//		RedisUtil.setJedisVal(customer.getCustId().toString(), jedisval);
//		return key;
//	}

}
